<script>
    import { BeButton, BeForm, BeFormItem, BeInput, showNotice } from '@brewer/beerui';
    import { onDestroy } from 'svelte'
    import localforage from 'localforage'

    // export let speed;
    // export let manual;

    let resEl;
    let cur = null;
    let Hlist = [];
    let hIndex = -1;
    let timer = null;
    let NewSZ = ''
    let curText;
    let curAttr;

    $: {
        curText = Object.keys(cur || {})[0]
        curAttr =  Object.values(cur || {})[0]
    }

    const TOWDAY = 2 * 24 * 60 * 60 *1000
    const TODAY = new Date().getTime()

    // $: cur = Hlist[hIndex] || ''

    //生字
    const shengzi = localforage.createInstance({
        name: 'shengzi',
        storeName:'shengzi'
    })
    //之前认识的字
    const oldSZ = localforage.createInstance({
        name: 'shengzi',
        storeName:'oldSZ'
    })
    //近期不再出现的字
    const overSZ = localforage.createInstance({
        name: 'shengzi',
        storeName:'overSZ'
    })

    const addNewSZ = (w)=>{
        return shengzi.setItem(w, {
            successCount: 0,
            important: false,
            lastSuccessTime: TODAY
        })
    }
    const addOldSZ = (w, attr={})=>{
        return oldSZ.setItem(w, {
            successCount: 1,
            important: attr.important===undefined?false:attr.important,
            lastSuccessTime: TODAY
        })
    }


    const add = ()=>{
        if(!NewSZ) return;
        addNewSZ(NewSZ).then(res=>{
            showNotice({
                toast: true,
                message: '添加成功',
                duration: 1500,
                type:'success'
            });
            NewSZ = ''
        })
    }

    function fullScreen(){
        resEl.requestFullscreen()
    }
    function exitScreen(){
        document.exitFullscreen()
    }

    //今日新的生字
    let newSZ = []
    //错字
    let errSZ = []
    //之前认识但还没到3次, 且以过期的字或者重点字
    let prevList = []
    let prevListMaxLength = 20

    let overList = []
    let overListMaxLength = 20

    let init = false

    async function initList(){
        const szp = shengzi.iterate((value, key)=>{
            newSZ.push({
                [key]:value
            })
        }).then(()=>{
            newSZ = newSZ
        })
        const osp = oldSZ.iterate((value, key)=>{
            if((TODAY - value.lastSuccessTime) > TOWDAY || value.important){
                prevList.push({
                    [key]:value
                })
            }
        }).then(()=>{
            prevList = prevList.filter((item,index)=> index < prevListMaxLength)
        })
        return Promise.all([szp,osp]).then(()=>{
            init = true
            console.log('init',newSZ, prevList)
        })
    }


    let part = 1;   //1: 新生字阶段;2: 错字阶段;3: 回顾阶段;
    //1 -> 2... -> 3 -> 2...
    function next() {
        if(part === 1){
            if(Hlist.length === 0){
                Hlist = newSZ.sort(()=> Math.random() - 0.5)
                newSZ = []
            }
        }

        if(part === 2){
            if(Hlist.length === 0){
                Hlist = errSZ.sort(()=> Math.random() - 0.5)
                errSZ = []
            }
        }

        if(part === 3){
            
        }
        cur = Hlist.shift();
        console.log(cur)
    }

    function theEnd(){
        alert('end')
    }

    function nextHandler(p){
        if(Hlist.length === 0){
            console.log(part)
            part = p || 2
        }
        next()
    }

    function error(){
        if(!init) return;
        if(part === 1 || part == 3){
            errSZ.push(cur);
            nextHandler()
        }else{
            errSZ.push(cur);
            nextHandler(2)
        }
        
    }

    function successHandler(){
        oldSZ.getItem(curText).then(c=>{
            if(c){
                c.successCount += 1
                c.lastSuccessTime = TODAY

                if(c.successCount > 3 && !c.important){
                    overSZ.setItem(curText, c)
                }else{
                    oldSZ.setItem(curText, c)
                }
            }else{
                addOldSZ(curText, curAttr)
            }
        })

        shengzi.removeItem(curText)
    }
    function success(){
        if(!init) return;
        successHandler()
        if(part === 1 || part === 3){
            if(Hlist.length === 0){
                if(errSZ.length === 0){
                    theEnd()
                }else{
                    nextHandler()
                }
            }else{
                nextHandler()
            }
        }else if(part === 2){
            if(Hlist.length === 0 && errSZ.length === 0){
                theEnd()
            }else{
                nextHandler(2)
            }
        }
    }

    function setImportant(){

    }

    async function action(){
        if(!init){
            await initList()
            next()
        }else{
            part = 1
            errSZ = []
            newSZ = []
            Hlist = []
            prevList = []

            await initList()
            next()
        }
        
    }
    

</script>


<div class="sz_com">
    <div class="sz_ctrl">
        <BeForm labelWidth="130px">
            
            <div class='flex'>
				<BeFormItem label="新增生字：">
                    <BeInput type="text" size="small" bind:value={NewSZ} />
                </BeFormItem>
                <BeFormItem>
                    <BeButton size="small" style="margin-left:20px" on:click={add}>添加</BeButton>
                </BeFormItem>
			</div>
            <BeFormItem label="复习数量：">
                <BeInput type="text" size="small" bind:value={overListMaxLength} />
            </BeFormItem>
            <BeFormItem style="margin-top:20px;text-align: center;">
                <BeButton type="success" style="" on:click={action}>开始学生字</BeButton>
                <BeButton style="margin-left:20px;" on:click={action}>复习很久以前的生字</BeButton>
            </BeFormItem>
        </BeForm>
    </div>
    <div class="shengziview" bind:this={ resEl }>
        <div class="num">
            <span class="n_p">{curText || '未开始'}</span>
        </div>
        <div class="tc">
            <BeButton class="err" type="danger" on:click={error}>错误</BeButton>
            <BeButton class="right" type="success" on:click={success}>正确</BeButton>
            <BeButton class="imp" type="warning" on:click={setImportant}>设为重点</BeButton>
        </div>
        <div class="impbox">
            <BeButton class="full" on:click={fullScreen}>全屏</BeButton>
            <BeButton class="exit_full" on:click={exitScreen}>取消全屏</BeButton>
        </div>
    </div>
</div>

<style>
    .impbox{
        display: flex;
        justify-content: center;
        margin-top: 16px;
    }
    
</style>